//
//  M4BankVerficationViewController.swift
//  M4
//
//  Created by YuChuang on 2024/8/21.
//

import UIKit
import ActiveLabel
import AdjustSdk

class M4BankVerficationViewController: M4BaseViewController {
    
    @IBOutlet weak var M4BankVerMobile: UILabel!
    
    @IBOutlet weak var M4BankVerContact: ActiveLabel!
    
    @IBOutlet weak var M4BankVerContactTop: NSLayoutConstraint!
    
    @IBOutlet weak var M4BankVerContactHeight: NSLayoutConstraint!
    
    @IBOutlet weak var M4BankVerCodeView: UIView!
    
    @IBOutlet weak var M4BankVerCodeTF: UITextField!
    
    @IBOutlet weak var M4BankVerCodeButton: UIButton!
    
    @IBOutlet weak var M4BankVerVoiceButton: UIButton!
    
    private var M4BankSmsTimer: Timer?
    private var M4BankSmsTimeInterval: TimeInterval = 0
    private var M4BankVozTimer: Timer?
    private var M4BankVozTimeInterval: TimeInterval = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white
        M4NavBarColor = .white
        M4NavTitle(M4Title: "Inicia sesión", M4NavTitleColor: COLOR_333333)
        M4BackIcon = "icon_back_black"
        M4NavRightItem()
        M4BankVerMobile.text = "+52\(M4UserDataManager.m4UserShare.M4UserMobile)"
        let activeHandle = ActiveType.custom(pattern: "contactar al servicio")
        M4BankVerContact.enabledTypes = [activeHandle]
        M4BankVerContact.text = "Si no puede verificar, haga clic para contactar al servicio de atención al cliente!"
        M4BankVerContact.customColor[activeHandle] = COLOR_00479D
        M4BankVerContact.handleCustomTap(for: activeHandle) { element in
            let alert = M4KFAlertView()
            alert.didTapKFzxHandle = {
                
                
            }
            alert.M4AlertViewShow()
        }
        M4BankVerContact.isHidden = true
        M4BankVerContactHeight.constant = 0
        M4BankVerContactTop.constant = 0
        M4BankVerCodeView.layer.cornerRadius = 2
        M4BankVerCodeView.layer.borderColor = COLOR_CCCCCC.cgColor
        M4BankVerCodeView.layer.borderWidth = 0.5
        M4BankVerCodeTF.keyboardType = .numberPad
        M4BankVerCodeTF.delegate = self
    }
    
    
    @IBAction func M4BankVerSendSms(_ sender: UIButton) {
        M4SendMSMCodeNet()
    }
    
    @IBAction func M4BankVerSendVoiceCode(_ sender: UIButton) {
        M4SendVozCodeNet()
    }
    
    @objc private func M4BankTimerCut(timer: Timer) {
        if timer == M4BankSmsTimer {
            M4BankSmsTimeInterval -= 1
            if M4BankSmsTimeInterval <= 0 {
                M4BankStopTimer(timer: timer)
                M4BankVerCodeButton.backgroundColor = COLOR_00479D
                M4BankVerCodeButton.setTitle("Conseguir", for: .normal)
                M4BankVerCodeButton.setTitleColor(.white, for: .normal)
                M4BankVerCodeButton.M4EventUnavailable = false
                M4BankVerContact.isHidden = false
                M4BankVerContactHeight.constant = 20
                M4BankVerContactTop.constant = 20
            }
            else {
                M4BankVerCodeButton.backgroundColor = COLOR_EFEFEF
                let seconds = Int(M4BankSmsTimeInterval) % 60
                let titleStr = "\(String(format: "%02ds", seconds))"
                M4BankVerCodeButton.setTitle("Reenviar \(titleStr)", for: .normal)
                M4BankVerCodeButton.setTitleColor(COLOR_999999, for: .normal)
            }
        }
        else {
            M4BankVozTimeInterval -= 1
            if M4BankVozTimeInterval <= 0 {
                M4BankStopTimer(timer: timer)
                M4BankVerVoiceButton.setTitle("Obtener la verificación por mensaje de voz >", for: .normal)
                M4BankVerVoiceButton.setTitleColor(COLOR_00479D, for: .normal)
                M4BankVerVoiceButton.M4EventUnavailable = false
            }
            else {
                M4BankVerVoiceButton.setTitleColor(COLOR_999999, for: .normal)
                let seconds = Int(M4BankVozTimeInterval) % 60
                let titleStr = "\(String(format: "%02ds", seconds))"
                M4BankVerVoiceButton.setTitle("Obtener la verificación por mensaje de voz \(titleStr) >", for: .normal)
            }
        }
    }
    
    private func M4BankStopTimer(timer: Timer) {
        if timer == M4BankSmsTimer {
            M4BankSmsTimer?.invalidate()
            M4BankSmsTimer = nil
            M4BankSmsTimeInterval = 0
        }
        else {
            M4BankVozTimer?.invalidate()
            M4BankVozTimer = nil
            M4BankVozTimeInterval = 0
        }
    }
    

}

extension M4BankVerficationViewController {
    
    private func M4SendMSMCodeNet() {
        let phone = "52\(M4UserDataManager.m4UserShare.M4UserMobile)"
        let param: [String : Any] = ["WIxTO": "ESP", "ChtW": M4UserDataManager.m4UserShare.M4Itemcode, "Taxz": phone, "JYJBl": "6", "IrWk": "adjust", "JtJQG": M4UserDataManager.m4UserShare.adjustIdfa, "Hsan": M4UserDataManager.m4UserShare.adjustAdid, "AfgFS": M4UserDataManager.m4UserShare.adjustIdfv, "WJVWZb": "Apple"]
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4smsCode, .post, params: param)) { model in
            if model.code == 1 {
                if self.M4BankSmsTimer == nil {
                    self.M4BankSmsTimeInterval = 60
                    self.M4BankSmsTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.M4BankTimerCut(timer:)), userInfo: nil, repeats: true)
                    RunLoop.main.add(self.M4BankSmsTimer!, forMode: .common)
                }
            }
            else {
                self.M4BankVerCodeButton.M4EventUnavailable = false
                self.view.makeToast(model.message, position: .center)
            }
        }
    }
    
    
    private func M4SendVozCodeNet() {
        let phone = "52\(M4UserDataManager.m4UserShare.M4UserMobile)"
        let param: [String : Any] = ["NTFJSQWe": "ESP", "IKu": M4UserDataManager.m4UserShare.M4Itemcode, "WvUJSd": phone, "Sfag": "6", "WcavLQlhe": "adjust", "XdJvZ": M4UserDataManager.m4UserShare.adjustIdfa, "SXGJ": M4UserDataManager.m4UserShare.adjustAdid, "OSjvU": M4UserDataManager.m4UserShare.adjustIdfv, "USg": "Apple"]
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4vozCode, .post, params: param)) { model in
            if model.code == 1 {
                if self.M4BankVozTimer == nil {
                    self.M4BankVozTimeInterval = 60
                    self.M4BankVozTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.M4BankTimerCut(timer:)), userInfo: nil, repeats: true)
                    RunLoop.main.add(self.M4BankVozTimer!, forMode: .common)
                }
            }
            else {
                self.M4BankVerVoiceButton.M4EventUnavailable = false
                self.view.makeToast(model.message, position: .center)
            }
        }
    }
    
    private func M4BankCodeVerficationNet() {
        let para: [String : Any] = ["nkjSD": "ESP", "YUdfx": M4UserDataManager.m4UserShare.M4Itemcode, "OycdS": M4UserDataManager.m4UserShare.M4Token, "TjkcdD": "52\(M4UserDataManager.m4UserShare.M4UserMobile)", "ksHHf": M4BankVerCodeTF.text ?? ""]
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4BankCodeVer, .post, params: para)) { model in
            if model.code == 1 {
                let page = M4FourInfoViewController()
                page.isInfoPage = false
                self.navigationController?.pushViewController(page, animated: true)
            }
            else {
                self.view.makeToast(model.message, position: .center)
            }
        }
    }
}

extension M4BankVerficationViewController: UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard let textString = textField.text else {return true}
        let length = textString.count + string.count - range.length
        if length == 4 {
            textField.text = textString + string
            textField.endEditing(true)
        }
        return true
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        if textField.text?.count == 4 {
            M4BankCodeVerficationNet()
        }
    }
    
}
